/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-08-29 17:45:26
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-09-27 07:56:23
 * @FilePath: /react18-vite-admin/src/store/modules/settings.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { create } from 'zustand';
import { generate } from '@ant-design/colors';

import {
    getThemeMode,
    setThemeMode as setThemeModeCache,
    getThemePrimary,
    setThemePrimary,
    getAppSettings,
    setAppSettings
} from '@/utils';
import type { SettingsStore, ColorConfigType } from '@/typings/store/settings';
import defaultSettings from '@/settings';

import { ColorConfig, camelToKebab } from './theme';

const getCssVarObject = (
    theme: ColorConfigType,
    themeMode: AppThemeModeType
): Record<string, string> => {
    const cssVarObject: Record<string, string> = {};
    const themeColorKeys = Object.keys(
        theme.color
    ) as (keyof typeof theme.color)[];
    themeColorKeys.forEach((key) => {
        cssVarObject[`--c-${camelToKebab(key)}`] =
            theme!.color[key][themeMode]!;
        cssVarObject[`--c-${camelToKebab(key)}-dark`] = theme!.color[key].dark!;
        cssVarObject[`--c-${camelToKebab(key)}-default`] =
            theme!.color[key].default!;
    });
    const themeBackgroundKeys = Object.keys(
        theme.background
    ) as (keyof typeof theme.background)[];
    themeBackgroundKeys.forEach((key) => {
        cssVarObject[`--bg-${camelToKebab(key)}`] =
            theme!.background[key][themeMode]!;
        cssVarObject[`--bg-${camelToKebab(key)}-dark`] =
            theme!.background[key].dark!;
        cssVarObject[`--bg-${camelToKebab(key)}-default`] =
            theme!.background[key].default!;
    });
    themeColorKeys.forEach((key) => {
        cssVarObject[`--bg-${camelToKebab(key)}`] =
            theme!.color[key][themeMode]!;
        cssVarObject[`--bg-${camelToKebab(key)}-dark`] =
            theme!.color[key].dark!;
        cssVarObject[`--bg-${camelToKebab(key)}-default`] =
            theme!.color[key].default!;
    });
    const themeTextColorKeys = Object.keys(
        theme.textColor
    ) as (keyof typeof theme.textColor)[];
    themeTextColorKeys.forEach((key) => {
        cssVarObject[`--c-${camelToKebab(key)}`] =
            theme!.textColor[key][themeMode]!;
        cssVarObject[`--c-${camelToKebab(key)}-dark`] =
            theme!.textColor[key].dark!;
        cssVarObject[`--c-${camelToKebab(key)}-default`] =
            theme!.textColor[key].default!;
    });

    const themeTextKeys = Object.keys(
        theme.text
    ) as (keyof typeof theme.text)[];
    themeTextKeys.forEach((key) => {
        cssVarObject[`--text-${camelToKebab(key)}`] = theme!.text[key];
    });
    return cssVarObject;
};

const getThemeObject = (config: ColorConfigType) => {
    const keys = Reflect.ownKeys(
        config.color
    ) as (keyof ColorConfigType['color'])[];
    const themeObject: typeof config = JSON.parse(JSON.stringify(config));

    keys.forEach((key) => {
        if (themeObject.color[key].dark === undefined) {
            themeObject.color[key].dark = generate(
                themeObject.color[key].default,
                {
                    theme: 'dark',
                    backgroundColor: themeObject.background.background.dark
                }
            )[5];
        }
    });
    return themeObject;
};

export const useSettingsStore = create<SettingsStore>((set, get) => {
    const themeMode = getThemeMode() ?? defaultSettings.theme;
    if (themeMode === 'dark') {
        document.documentElement.classList.add('dark');
    } else {
        document.documentElement.classList.remove('dark');
    }

    let theme = undefined as ColorConfigType | undefined;
    const colorConfig = new ColorConfig();
    const primaryColor = getThemePrimary() ?? defaultSettings.themeColor;
    if (primaryColor) {
        colorConfig.color.primary.default = primaryColor;
    }
    theme = getThemeObject(colorConfig);

    const appSettings = getAppSettings() ?? defaultSettings;

    return {
        theme,
        themeMode,
        cssVarObject: getCssVarObject(theme, themeMode),
        setTheme(config) {
            const themeObject = getThemeObject(config);
            // 本地存储主题色
            const themePrimary = themeObject.color.primary.default;
            setThemePrimary(themePrimary);
            setAppSettings({
                ...(getAppSettings() ?? defaultSettings),
                themeColor: themePrimary
            });
            set((state) => {
                return {
                    theme: themeObject,
                    cssVarObject: getCssVarObject(themeObject, state.themeMode)
                };
            });
        },
        setThemePrimary(primaryColor) {
            const colorConfig = new ColorConfig();
            colorConfig.color.primary.default = primaryColor;
            get().setTheme(colorConfig);
        },
        setThemeMode(mode) {
            if (mode === 'dark') {
                document.documentElement.classList.add('dark');
            } else {
                document.documentElement.classList.remove('dark');
            }
            set((state) => {
                if (state.theme === undefined)
                    throw new Error('[./store/modules/app]theme还未初始化');
                return {
                    themeMode: mode,
                    cssVarObject: getCssVarObject(state.theme, mode)
                };
            });
            setThemeModeCache(mode);
            setAppSettings({
                ...(getAppSettings() ?? defaultSettings),
                theme: mode
            });
        },
        layout: appSettings.layout,
        setLayout(layout) {
            set({
                layout
            });
            setAppSettings({
                ...(getAppSettings() ?? defaultSettings),
                layout
            });
        },
        showTagsView: appSettings.tagsView,
        setShowTagsView(showTagsView) {
            set({
                showTagsView
            });
            setAppSettings({
                ...(getAppSettings() ?? defaultSettings),
                tagsView: showTagsView
            });
        },
        fixedHeader: appSettings.fixedHeader,
        setFixedHeader(fixedHeader) {
            set({
                fixedHeader
            });
            setAppSettings({
                ...(getAppSettings() ?? defaultSettings),
                fixedHeader
            });
        },
        sidebarLogo: appSettings.sidebarLogo,
        setSidebarLogo(sidebarLogo) {
            set({
                sidebarLogo
            });
            setAppSettings({
                ...(getAppSettings() ?? defaultSettings),
                sidebarLogo
            });
        },
        showSettings: appSettings.showSettings,
        settingsVisible: false,
        setSettingsVisible(settingsVisible) {
            set({
                settingsVisible
            });
        },
        watermarkEnabled: appSettings.watermarkEnabled,
        setWatermarkEnabled(watermarkEnabled) {
            set({
                watermarkEnabled
            });
            setAppSettings({
                ...(getAppSettings() ?? defaultSettings),
                watermarkEnabled
            });
        }
    };
});
